#include <iostream>
#include <cstdio>
#include <cassert>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>

using namespace std;

void test1(){
    pid_t id = fork();
    assert(id!=-1);
    if(id == 0)
    {
        printf("[%d]: 子进程正在运行!\n", getpid());
        sleep(3);
        printf("[%d]: 子进程退出!\n", getpid());
        exit(0);
    }

    while(true)
    {
        printf("[%d]: 父进程正在运行!\n", getpid());
        sleep(1);
    }
}

void test2(){
    signal(SIGCHLD, SIG_IGN); //手动忽略
    pid_t id = fork();
    assert(id!=-1);
    if(id == 0)
    {
        printf("[%d]: 子进程正在运行!\n", getpid());
        sleep(3);
        printf("[%d]: 子进程退出!\n", getpid());
        exit(0);
    }

    while(true)
    {
        printf("[%d]: 父进程正在运行!\n", getpid());
        sleep(1);
    }
}

void handler(int signum){
    printf("[%d]: 捕获了一个信号: %d\n", getpid(), signum);
    pid_t cpid = 0;
    while((cpid = waitpid(-1, nullptr, WNOHANG)) > 0)
    {
        printf("[%d]: 子进程退出，cpid: %d\n", getpid(), cpid);
    }
}

void test3(){
    signal(SIGCHLD, handler); //自定义捕捉
    pid_t id = fork();
    assert(id!=-1);
    if(id == 0)
    {
        printf("[%d]: 子进程正在运行!\n", getpid());
        sleep(3);
        printf("[%d]: 子进程退出!\n", getpid());
        exit(0);
    }

    while(true)
    {
        printf("[%d]: 父进程正在运行!\n", getpid());
        sleep(1);
    }
}

int main(){
    test3();
    return 0;
}